﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GoodMan.Portal.WebLogic;
using GoodMan.Infrastructure.Entities.Enum;
using GoodMan.Portal.Biz;
using GoodMan.Infrastructure.Entities.Entity;
using GoodMan.Portal.Web.Areas.WorkSpace.Models;
using GoodMan.Tool.Framework;

namespace GoodMan.Portal.Web.Areas.WorkSpace.Controllers
{
    /// <summary>
    /// 楼栋管理员
    /// </summary>
    [ErrorHandle]
    [Warp]
    [Auth(UserRole.Staff)]
    public class StaffController : Controller
    {
        //
        // GET: /WorkSpace/Staff/

        public ActionResult Index()
        {
            return View();
        }

        #region 用户

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult RegisterUserInfoList(UserModel model, int page = 0)
        {
            User user = new User().Find(c => c.UserName.Equals(HttpContext.User.Identity.Name));
            
            model.FloorId = user.FloorId;
            model.SystemRole = 1;
            ViewBag.UserList = UserBiz.GetAllUserByWhere(page, 10, model.SystemRole, model.FloorId, model.Gender, -1, model.Dormitory, model.NickName, model.RealName);
            ViewBag.DormitoryList = new Dormitory().FindAll();
            ViewBag.SearchModel = model;
            return View();
        }


        /// <summary>
        /// 用户详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UserInfo(string u, int page = 0, int r = 0)
        {
            ViewBag.page = page;
            ViewBag.Register = r;
            ViewBag.User = new User().Find(u);
            return View();
        }
        #endregion

        #region 订单管理

        #region 订单统计
        /// <summary>
        /// 查询订单列表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult OrdersStatistics(int page = 0, string realName = "", string dtstart = "", string dtend = "", int status = -1,int self=0)
        {
            //int domid = SupportBiz.IsOnDuty(System.Web.HttpContext.Current.User.Identity.Name);
            int domid = new User().Find(System.Web.HttpContext.Current.User.Identity.Name).FloorId;
            int orderCount = 0;
            decimal totalPrice = 0.00m;
            bool isSelf = self == 1 ? true : false;
            var orderList = OrderBiz.OrderQuery(UserRole.Staff, domid, realName, dtstart, dtend, status, isSelf, page, 10, ref orderCount, ref totalPrice);
            ViewBag.OrderList = orderList;

            #region 回填数据
            ViewBag.realName = realName;
            ViewBag.dtstart = dtstart;
            ViewBag.dtend = dtend;
            ViewBag.status = status;
            ViewBag.orderCount = orderCount;
            ViewBag.totalPrice = totalPrice;
            ViewBag.self = self;
            #endregion
            return View();
        }
        public ActionResult OrderDetail(int id)
        {
            Order order = new Order().Find(id.ToString());
            List<OrderDetail> orderDetailList = new OrderDetail().FindAll(c => c.OrderId == id);
            string name = System.Web.HttpContext.Current.User.Identity.Name;
            var user = new User().Find(name);
            ViewBag.User = user;
            ViewBag.Order = order;
            ViewBag.OrderDetail = orderDetailList;
            ViewBag.OrderHistory = new OrderHistory().FindAll(c => c.OrderId == order.Id);
            return View();
        }
        #endregion

        #region 待处理订单
        /// <summary>
        /// 查询【待处理】（状态为3 - 等待发货）订单
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult WaitForHandleOrder(int page = 0, string realName = "", string dtstart = "", string dtend = "")
        {
            int domid = SupportBiz.IsOnDuty(System.Web.HttpContext.Current.User.Identity.Name);
            int orderCount = 0;
            decimal totalPrice = 0.00m;
            var orderList = OrderBiz.OrderQuery(UserRole.Staff, domid, realName, dtstart, dtend, 3,false, page, 10, ref orderCount, ref totalPrice);
            ViewBag.OrderList = orderList;

            #region 回填数据
            ViewBag.realName = realName;
            ViewBag.dtstart = dtstart;
            ViewBag.dtend = dtend;
            ViewBag.status = 3;
            ViewBag.orderCount = orderCount;
            ViewBag.totalPrice = totalPrice;
            #endregion
            return View();
        }


        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult ModifyOrder(int id = 0, int status = 3, int page = 0)
        {
            ViewBag.isSuccess = OrderBiz.ModifyOrderStatus(id, status);
            return Redirect("/WorkSpace/Staff/WaitForHandleOrder?page=" + page);
        }
        #endregion

        #endregion

        #region 个人信息
        public ActionResult myduty(int page =0)
        {
            var list = new Duty().FindAll(c=>true,c=>c.Id,page,10);
            ViewBag.MyDuty = new ItemListBox<Duty>(list)
                .BuildPage(new Duty().Count(c=>true), page, 10,
                new PageParameter() { 
                    Style="workspace"
                });
            return View();
        }
        /// <summary>
        /// 个人信息首页
        /// </summary>
        /// <returns></returns>
        public ActionResult MyInfo()
        {
            string userName = HttpContext.User.Identity.Name;
            ViewBag.UserModel = new User().Find(userName);
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }

        /// <summary>
        /// 修改个人信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MyInfo(UserModel model)
        {
            var user = new User().Find(model.UserName);

            if (user != null)
            {
                user.Gender = model.Gender == 1 ? Gender.Male : Gender.Female;
                user.IdCardNo = model.IdCardNo;
                user.RealName = model.RealName;
                user.NickName = model.NickName;
                user.Phone = model.Phone;
                user.QQ = model.QQ;
                user.Dormitory = model.Dormitory;
                user.FloorId = model.FloorId;

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("管理员：{0}修改个人信息失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改信息失败！";
                    return View();
                }
                ViewBag.UserModel = user;
                ViewBag.Error = "";
            }
            ViewBag.UserModel = user;
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }
        public ActionResult Secret()
        {
            return View();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="Confirm"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Secret(string Confirm)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);

            if (user != null)
            {
                user.Password = AesAlgorithm.Encrypt(Confirm);

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("管理员：{0}修改密码失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改密码失败！";
                    return View();
                }
            }
            ViewBag.Error = "";
            return View();
        }

        public ActionResult MyRebate(int page = 0)
        {
            var list = RebateReportBiz.MyRebate(page);
            ViewBag.data = list;
            return View();
           
        }
        #endregion

        #region 线下销售
        public ActionResult OutLineSales(bool isSuccess=true,string message="",string productCode="")
        {
            ViewBag.Data = ProductBiz.GetProductByPoductCode(productCode);
            ViewBag.ProductCode = productCode;

            ViewBag.Message = isSuccess;
            ViewBag.MessageStr = message;
            return View();
        }
        //[HttpPost]
        //public ActionResult SearchProductByCode(string productCode)
        //{
        //    return Redirect("/WorkSpace/Staff/OutLineSales?productCode=" + productCode);
        //}
        [HttpPost]
        public ActionResult OutLineBuy(string code="", int salsecount=0,int productId=0)
        {
            if (salsecount < 1)
            {
                //ViewBag.Message = false;
               string messageStr = "请输入购买数量";
               return Redirect("/WorkSpace/Staff/OutLineSales?productCode=" + code + "&isSuccess=false&message=" + messageStr);
            }
            else
            {
                
                try
                {
                    int productRemain = ProductBiz.GetProductRemain(productId);

                    if (productRemain < salsecount)//库存不够
                    {
                        ViewBag.Message = false;
                        string messageStr = "库存不足（剩余:" + productRemain + ")";
                         
                        return Redirect("/WorkSpace/Staff/OutLineSales?productCode=" + code + "&isSuccess=false&message=" + messageStr);
                        // return View("ProductItemView");
                    }
                    else
                    {
                        var product = new Product().Find(productId.ToString());
                         
                        var orderDetailList = new List<OrderDetail>();
                        var orderDetail = new OrderDetail();
                        var policy = PolicyBiz.GetSpecialPolicy(productId);//获取特卖策略信息
                        if (policy == null)
                        {
                            policy = new Policy().Find(c => c.ProductId == productId && c.PolicyType == 1);
                        }
                        orderDetail.AreaCode = product.AreaCode;
                        orderDetail.Num = salsecount;
                        orderDetail.PolicyId = policy.Id;
                        orderDetail.Price = policy.Price;
                        orderDetail.ProductId = product.Id;
                        orderDetail.ProductName = product.ProductName;
                        orderDetail.ProductSubType = product.ProductSubType;
                        orderDetail.ProductType = product.ProductType;

                        orderDetail.productRemain = productRemain;

                        orderDetailList.Add(orderDetail);

                        var order = new Order();
                        string name = System.Web.HttpContext.Current.User.Identity.Name;
                        var User = new User().Find(name);
                        var floor = new Dormitory().Find(User.FloorId.ToString());
                        order.AssemblingInfo = floor.Name + "   " + User.Dormitory + "     " + User.RealName + "(电话:" + User.Phone + ")";//配送信息：张三（手机：13100000000） 楼栋 1310
                        order.DormitoryID = User.FloorId;
                        order.OrderCode = OrderBiz.OrderCodeGenerator(AreaCode.Normal);
                        order.OrderDate = DateTime.Now;
                        order.Phone = User.Phone;
                        order.ProductDescript = product.ProductName + "(" + product.ProductCode+ ")*" + salsecount;// 所购买的产品简单描述 例：（友友泡凤爪(125g)*2、统一老坛酸菜牛肉面（桶）*1、）格式为产品名称[(规格)]*购买数量
                        order.Status = OrderStatus.Completed;
                        order.TotalPrice = policy.Price * salsecount;
                        order.UserName = name;
                        order.AreaCode = AreaCode.Normal;
                        order.HandleUser = name;
                        order.Payway = PayWay.Cash;
                        order.BusinessId = 0;
                        order.Remark = "线下销售";

                        var orderHistory = new OrderHistory();
                        orderHistory.CreateTime = DateTime.Now;
                        orderHistory.CurrentStatue = OrderStatus.Completed;
                        orderHistory.Remark = "线下销售";

                        var orderTemp = order.PostAdd();
                        foreach (var detail in orderDetailList)
                        {

                            detail.OrderId = orderTemp.Id;
                            detail.PostAdd();
                        }
                        orderHistory.OrderId = orderTemp.Id;
                        orderHistory.PostAdd();

                        var repertory = new ProductRepertory().Find(c => c.ProductId == productId && c.DormitoryId == User.FloorId);
                        if (repertory != null)
                        {
                            repertory.Remain -= salsecount;
                            repertory.PostModify();
                        }

                        ViewBag.Message = true;
                        string messageStr = "销售成功，订单号为：" + orderTemp.OrderCode;
                        return Redirect("/WorkSpace/Staff/OutLineSales?productCode=" + code + "&isSuccess=true&message=" + messageStr);
                    }
                    
                }
                catch (Exception e)
                {
                    LogHelper.Write(CommonLogger.System, LogLevel.Error, e);
                     
                    string messageStr = "对不起，出错了！请稍后重试或联系管理员。";
                    return Redirect("/WorkSpace/Staff/OutLineSales?productCode=" + code + "&isSuccess=false&message=" + messageStr);
                }
            }
        }

        #endregion
    }
}
